package com.nulldev.util.security.encryptAPI.impls.rc4;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class RC4Cipher extends Encryptor {
	private final RC4 rc4;
	private final String key;

	public RC4Cipher(final String key) {
		super("encryptapi.tp.rc4", new String[]
			{ "RC4" }, key);
		this.rc4 = new RC4(key);
		this.key = key;
	}

	public RC4Cipher(final byte[] key) {
		super("encryptapi.tp.rc4", new String[]
			{ "RC4" }, key);
		this.key = new String(key);
		this.rc4 = new RC4(this.key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return this.rc4.encryptMessage(new String((byte[]) o), this.key);
		} else if (o instanceof String) {
			return this.rc4.encryptMessage((String) o, this.key);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return Base64.encodeBase64String(this.rc4.encryptMessage(new String((byte[]) o), this.key));
		} else if (o instanceof String) {
			return Base64.encodeBase64String(this.rc4.encryptMessage((String) o, this.key));
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String s) {
		return this.rc4.decryptMessage(Base64.decodeBase64(s), this.key);
	}

	@Override
	public byte[] decryptToBytes(byte[] b) {
		return this.rc4.decryptMessage(b, this.key).getBytes();
	}

	@Override
	public byte[] getKey() {
		return this.key.getBytes();
	}

	@Override
	public String getKeyAsString() {
		return Base64.encodeBase64S(this.key);
	}

}
